Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Write your Algorithm
  • Step 6: Test Your Algorithm

Step 0: Import Datasets

Make sure that you've downloaded the required human and dog datasets:

Note: if you are using the Udacity workspace, you DO NOT need to re-download these - they can be found in the /data folder as noted in the cell below.

  • Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dog_images.

  • Download the human dataset. Unzip the folder and place it in the home directory, at location /lfw.

Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.

In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.

In [ ]:
 
In [10]:
import numpy as np
from glob import glob

# load filenames for human and dog images
human_files = np.array(glob("/data/lfw/*/*"))
dog_files = np.array(glob("/data/dog_images/*/*/*"))

# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
There are 13233 total human images.
There are 8351 total dog images.

Step 1: Detect Humans

In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.

OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [11]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[0])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [12]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: (You can print out your results and/or write your percentages in this cell)

There is a 98% recognition percentage for in the human_files images.

And a 17% recognition percentage in the dog_files images.

In [13]:
from tqdm import tqdm

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]

#-#-# Do NOT modify the code above this line. #-#-#
H_true = 0
D_true = 0

for i in (range(len(human_files_short))):
    if np.count_nonzero(face_detector(human_files_short[i])) == 1: 
        H_true = H_true + 1 

print("There are {} faces detected in the human folder.".format(H_true))
    
for i in range(len(dog_files_short)): 
    if np.count_nonzero(face_detector(dog_files_short[i])) == 1: 
        D_true = D_true + 1 
    
print("There are {} faces detected in the dog folder.".format(D_true))
There are 98 faces detected in the human folder.
There are 17 faces detected in the dog folder.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [ ]:
 

Step 2: Detect Dogs

In this section, we use a pre-trained model to detect dogs in images.

Obtain Pre-trained VGG-16 Model

The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.

In [15]:
import torch
import torchvision.models as models

# define VGG16 model
VGG16 = models.vgg16(pretrained=True)

# check if CUDA is available
use_cuda = torch.cuda.is_available()

# move model to GPU if CUDA is available
if use_cuda:
    VGG16 = VGG16.cuda()
Downloading: "https://download.pytorch.org/models/vgg16-397923af.pth" to /root/.torch/models/vgg16-397923af.pth
100%|██████████| 553433881/553433881 [00:09<00:00, 56602012.81it/s]

Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.

(IMPLEMENTATION) Making Predictions with a Pre-trained Model

In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.

Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.

In [16]:
from PIL import Image
import torchvision.transforms as transforms

def VGG16_predict(img_path):
    '''
    Use pre-trained VGG-16 model to obtain index corresponding to 
    predicted ImageNet class for image at specified path
    
    Args:
        img_path: path to an image
        
    Returns:
        Index corresponding to VGG-16 model's prediction
    '''
    
    ## Load and pre-process an image from the given img_path
    ## Return the *index* of the predicted class for that image
    image_transform=transforms.Compose([
                                    transforms.Resize(size = (224,224)),
                                    transforms.ToTensor(),
                                    transforms.Normalize([0.485, 0.456, 0.406], 
                                                         [0.229, 0.224, 0.225])])
    image_tensor= image_transform(Image.open(img_path).convert("RGB")).unsqueeze(0).float()
    if use_cuda:
        image_tensor=image_tensor.cuda()
    #output_index=VGG16(image_tensor).data.argmax()
    output_index = torch.max(VGG16(image_tensor), 1)[1].item()
    
    return output_index
print(VGG16_predict(dog_files[10]))
img = plt.imread(dog_files[10])
fig, ax = plt.subplots()
ax.imshow(img)
243
Out[16]:
<matplotlib.image.AxesImage at 0x7fdcbaf63a90>

(IMPLEMENTATION) Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).

Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [17]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    ## TODO: Complete the function.
    pred_class=VGG16_predict(img_path)
    if 151 <= pred_class <= 268: 
        return True
    else: 
        return False
    
print(dog_detector(dog_files[50]))
print(dog_detector(human_files[50]))
True
False

(IMPLEMENTATION) Assess the Dog Detector

Question 2: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

There are 1% dogs detected in the human folder.

There are 100% dogs detected in the dog folder.

In [18]:
H_true_1 = 0
D_true_1 = 0

for i in (range(len(human_files_short))):
    if np.count_nonzero(dog_detector(human_files_short[i])) == 1: 
        H_true_1 = H_true_1 + 1 

print("There are {} dogs detected in the human folder.".format(H_true_1))
    
for i in range(len(dog_files_short)): 
    if np.count_nonzero(dog_detector(dog_files_short[i])) == 1: 
        D_true_1 = D_true_1 + 1 
    
print("There are {} dogs detected in the dog folder.".format(D_true_1))
There are 1 dogs detected in the human folder.
There are 100 dogs detected in the dog folder.

We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [ ]:
 

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dog_images/train, dog_images/valid, and dog_images/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!

In [20]:
import os
from torchvision import datasets
import torchvision.transforms as transforms
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import torch

num_workers = 0

batch_size = 20

train_dir = ('/data/dog_images/train')
valid_dir = ('/data/dog_images/valid')
test_dir =  ('/data/dog_images/test')




data_transforms = {'train': transforms.Compose([transforms.RandomResizedCrop(224),
                                     transforms.RandomHorizontalFlip(p=0.5),
                                     transforms.RandomVerticalFlip(p=0.5),
                                     transforms.ToTensor(),
                                     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                              std=[0.229, 0.224, 0.225]),
                                     ]),
                   
                   
                   'valid': transforms.Compose([transforms.Resize(256),
                                     transforms.CenterCrop(224),
                                     transforms.ToTensor(),
                                     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                              std=[0.229, 0.224, 0.225])]),
                   
                   'test': transforms.Compose([transforms.Resize(size=(224,224)),
                                     transforms.ToTensor(), 
                                     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                              std=[0.229, 0.224, 0.225])])
                    
}
train_data= datasets.ImageFolder(train_dir, transform=data_transforms['train'])
valid_data= datasets.ImageFolder(valid_dir, transform=data_transforms['valid'])
test_data= datasets.ImageFolder(test_dir, transform=data_transforms['test'])

loader_scratch={ 'train' : torch.utils.data.DataLoader(train_data, batch_size=batch_size,num_workers=num_workers, shuffle=True),
              'valid' : torch.utils.data.DataLoader(valid_data,batch_size=batch_size, num_workers=num_workers,shuffle=False),
              'test'  : torch.utils.data.DataLoader(test_data,batch_size=batch_size,num_workers=num_workers,shuffle=False)
    
}

len(loader_scratch["train"])
len(loader_scratch["valid"])
len(loader_scratch["test"])
Out[20]:
42

Question 3: Describe your chosen procedure for preprocessing the data.

  • How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?
  • Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?
In [ ]:
 

Answer:

For the input I croped the image to a 224*224 tensor. For the trainingset I performed various augmentation steps. Since there are many similar breeds it is important to add some randomness to the learning process so that the modell is more robust. Since my training results were not very good at the beginning i tried several types of augementation such as random rotation or recoloring the image e.g. with RandomGreyScale. The best results I nevertheless got with randomcroping and random horizontal and vertical flip. This way i can prevent the modell from overfitting and get good learning results.

For the validation set i use a bigger input image and perfomed a centercrop.

The test set i did not augment at all.

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. Use the template in the code cell below.

In [21]:
import torch.nn as nn
import torch.nn.functional as F
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

# define the CNN architecture
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        ## Define layers of a CNN
        self.conv1 = nn.Conv2d(3, 32, 3, stride=2, padding=1)
        self.conv2 = nn.Conv2d(32, 64, 3, stride=2, padding=1)
        self.conv3 = nn.Conv2d(64, 128, 3, padding=1)

        # pool
        self.pool = nn.MaxPool2d(2, 2)
        
        # fully-connected
        self.fc1 = nn.Linear(7*7*128, 500)
        self.fc2 = nn.Linear(500, 133) 
        
        # drop-out
        self.dropout = nn.Dropout(0.33)
    
    def forward(self, x):
        ## Define forward behavior
        x = F.relu(self.conv1(x))
        x = self.pool(x)
        x = F.relu(self.conv2(x))
        x = self.pool(x)
        x = F.relu(self.conv3(x))
        x = self.pool(x)
        
        # flatten
        x = x.view(-1, 7*7*128)
        
        x = self.dropout(x)
        x = F.relu(self.fc1(x))
        
        x = self.dropout(x)
        x = self.fc2(x)
        return x

#-#-# You so NOT have to modify the code below this line. #-#-#

# instantiate the CNN
model_scratch = Net()

# move tensors to GPU if CUDA is available
if use_cuda:
    model_scratch.cuda()

print(model_scratch)
Net(
  (conv1): Conv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))
  (conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))
  (conv3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (fc1): Linear(in_features=6272, out_features=500, bias=True)
  (fc2): Linear(in_features=500, out_features=133, bias=True)
  (dropout): Dropout(p=0.33)
)

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.

Answer:

For the model architecture i used three convolutional layers in the beginning. I tried using more or less layers, but got good results with the stated number. For the first two layers I added a stride of 2 to downsize the images. With the padding of 1, I upgraded the image to a 225*225 tensor.

Afterwards i added two fully concected layers, where I use 500 inputs for the second one (classification layer), to produce in total 133 outputs. This is the number of different dog breeds in the data set.

Then I added a dropout of 0.33 to prevent the modell from overfitting. There i tried several values and got the best results with values between 0.25 and 0.35.

In the forwardfunction I put the image through multiple sequences of convolutional layers, activation functions(Relu) and pooling layers.

Lastly i flattened the image to a vector shape to put it into the fully conected layers, to be able to perform classification

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.

In [22]:
import torch.optim as optim

#Select loss function
criterion_scratch = nn.CrossEntropyLoss()

#select optimizer
optimizer_scratch = optim.SGD(model_scratch.parameters(), lr=0.005)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.

In [23]:
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path, last_validation_loss=None):
    """returns trained model"""
    # initialize tracker for minimum validation loss
    if last_validation_loss is not None:
        valid_loss_min = last_validation_loss
    else:
        valid_loss_min = np.Inf
    
    for epoch in range(1, n_epochs+1):
        # initialize variables to monitor training and validation loss
        train_loss = 0.0
        valid_loss = 0.0
        
        ###################
        # train the model #
        ###################
        model.train()
        for batch_idx, (data, target) in enumerate(loaders['train']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## find the loss and update the model parameters accordingly
            ## record the average training loss, using something like
            ## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))

            # initialize weights to zero
            optimizer.zero_grad()
            
            output = model(data)
            
            # calculate loss
            loss = criterion(output, target)
            
            # back prop
            loss.backward()
            
            # grad
            optimizer.step()
            
            train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
            
            if batch_idx % 100 == 0:
                print('Epoch %d, Batch %d loss: %.6f' %
                  (epoch, batch_idx + 1, train_loss))
            
        ######################    
        # validate the model #
        ######################
        model.eval()
        for batch_idx, (data, target) in enumerate(loaders['valid']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## update the average validation loss
            output = model(data)
            loss = criterion(output, target)
            valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))

            
        # print training/validation statistics 
        print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
            epoch, 
            train_loss,
            valid_loss
            ))
        
        ## save the model if validation loss has decreased
        if valid_loss < valid_loss_min:
            torch.save(model.state_dict(), save_path)
            print('Validation loss decreased ({:.6f} --> {:.6f}).  Saving model ...'.format(
            valid_loss_min,
            valid_loss))
            valid_loss_min = valid_loss
            
    # return trained model
    return model
In [27]:
# train the model
model_scratch = train(55, loader_scratch, model_scratch, optimizer_scratch, 
                      criterion_scratch, use_cuda, 'model_scratch.pt')
Epoch 1, Batch 1 loss: 4.154045
Epoch 1, Batch 101 loss: 4.232522
Epoch 1, Batch 201 loss: 4.242767
Epoch 1, Batch 301 loss: 4.242503
Epoch: 1 	Training Loss: 4.238366 	Validation Loss: 4.116579
Validation loss decreased (inf --> 4.116579).  Saving model ...
Epoch 2, Batch 1 loss: 4.262941
Epoch 2, Batch 101 loss: 4.220657
Epoch 2, Batch 201 loss: 4.213397
Epoch 2, Batch 301 loss: 4.207036
Epoch: 2 	Training Loss: 4.209570 	Validation Loss: 4.078922
Validation loss decreased (4.116579 --> 4.078922).  Saving model ...
Epoch 3, Batch 1 loss: 4.329472
Epoch 3, Batch 101 loss: 4.165270
Epoch 3, Batch 201 loss: 4.181840
Epoch 3, Batch 301 loss: 4.186222
Epoch: 3 	Training Loss: 4.191947 	Validation Loss: 4.052471
Validation loss decreased (4.078922 --> 4.052471).  Saving model ...
Epoch 4, Batch 1 loss: 3.876738
Epoch 4, Batch 101 loss: 4.160300
Epoch 4, Batch 201 loss: 4.156754
Epoch 4, Batch 301 loss: 4.186556
Epoch: 4 	Training Loss: 4.183954 	Validation Loss: 4.090836
Epoch 5, Batch 1 loss: 4.289435
Epoch 5, Batch 101 loss: 4.137759
Epoch 5, Batch 201 loss: 4.159803
Epoch 5, Batch 301 loss: 4.164265
Epoch: 5 	Training Loss: 4.168986 	Validation Loss: 4.015092
Validation loss decreased (4.052471 --> 4.015092).  Saving model ...
Epoch 6, Batch 1 loss: 4.292156
Epoch 6, Batch 101 loss: 4.157447
Epoch 6, Batch 201 loss: 4.146168
Epoch 6, Batch 301 loss: 4.149674
Epoch: 6 	Training Loss: 4.151644 	Validation Loss: 4.034774
Epoch 7, Batch 1 loss: 4.296741
Epoch 7, Batch 101 loss: 4.129118
Epoch 7, Batch 201 loss: 4.135910
Epoch 7, Batch 301 loss: 4.143466
Epoch: 7 	Training Loss: 4.146060 	Validation Loss: 4.009333
Validation loss decreased (4.015092 --> 4.009333).  Saving model ...
Epoch 8, Batch 1 loss: 4.011045
Epoch 8, Batch 101 loss: 4.129457
Epoch 8, Batch 201 loss: 4.118883
Epoch 8, Batch 301 loss: 4.130548
Epoch: 8 	Training Loss: 4.134436 	Validation Loss: 4.008624
Validation loss decreased (4.009333 --> 4.008624).  Saving model ...
Epoch 9, Batch 1 loss: 3.923716
Epoch 9, Batch 101 loss: 4.148718
Epoch 9, Batch 201 loss: 4.114599
Epoch 9, Batch 301 loss: 4.127096
Epoch: 9 	Training Loss: 4.122837 	Validation Loss: 4.007909
Validation loss decreased (4.008624 --> 4.007909).  Saving model ...
Epoch 10, Batch 1 loss: 3.996323
Epoch 10, Batch 101 loss: 4.101084
Epoch 10, Batch 201 loss: 4.119904
Epoch 10, Batch 301 loss: 4.113448
Epoch: 10 	Training Loss: 4.114589 	Validation Loss: 3.973319
Validation loss decreased (4.007909 --> 3.973319).  Saving model ...
Epoch 11, Batch 1 loss: 3.817734
Epoch 11, Batch 101 loss: 4.094447
Epoch 11, Batch 201 loss: 4.095167
Epoch 11, Batch 301 loss: 4.101816
Epoch: 11 	Training Loss: 4.105453 	Validation Loss: 4.017400
Epoch 12, Batch 1 loss: 3.581987
Epoch 12, Batch 101 loss: 4.067007
Epoch 12, Batch 201 loss: 4.092585
Epoch 12, Batch 301 loss: 4.084183
Epoch: 12 	Training Loss: 4.085915 	Validation Loss: 3.958421
Validation loss decreased (3.973319 --> 3.958421).  Saving model ...
Epoch 13, Batch 1 loss: 4.116815
Epoch 13, Batch 101 loss: 4.103006
Epoch 13, Batch 201 loss: 4.072643
Epoch 13, Batch 301 loss: 4.088889
Epoch: 13 	Training Loss: 4.085790 	Validation Loss: 3.938972
Validation loss decreased (3.958421 --> 3.938972).  Saving model ...
Epoch 14, Batch 1 loss: 3.793067
Epoch 14, Batch 101 loss: 4.039325
Epoch 14, Batch 201 loss: 4.054228
Epoch 14, Batch 301 loss: 4.048624
Epoch: 14 	Training Loss: 4.053633 	Validation Loss: 3.934696
Validation loss decreased (3.938972 --> 3.934696).  Saving model ...
Epoch 15, Batch 1 loss: 3.444201
Epoch 15, Batch 101 loss: 4.038531
Epoch 15, Batch 201 loss: 4.057528
Epoch 15, Batch 301 loss: 4.056023
Epoch: 15 	Training Loss: 4.054689 	Validation Loss: 3.965200
Epoch 16, Batch 1 loss: 4.117362
Epoch 16, Batch 101 loss: 4.048454
Epoch 16, Batch 201 loss: 4.074465
Epoch 16, Batch 301 loss: 4.050211
Epoch: 16 	Training Loss: 4.043939 	Validation Loss: 3.926442
Validation loss decreased (3.934696 --> 3.926442).  Saving model ...
Epoch 17, Batch 1 loss: 4.042056
Epoch 17, Batch 101 loss: 3.996269
Epoch 17, Batch 201 loss: 4.020735
Epoch 17, Batch 301 loss: 4.019855
Epoch: 17 	Training Loss: 4.022811 	Validation Loss: 3.991698
Epoch 18, Batch 1 loss: 4.201474
Epoch 18, Batch 101 loss: 4.031946
Epoch 18, Batch 201 loss: 4.034417
Epoch 18, Batch 301 loss: 4.023505
Epoch: 18 	Training Loss: 4.022943 	Validation Loss: 3.891064
Validation loss decreased (3.926442 --> 3.891064).  Saving model ...
Epoch 19, Batch 1 loss: 3.715024
Epoch 19, Batch 101 loss: 3.983795
Epoch 19, Batch 201 loss: 3.987623
Epoch 19, Batch 301 loss: 4.010357
Epoch: 19 	Training Loss: 4.009434 	Validation Loss: 3.876549
Validation loss decreased (3.891064 --> 3.876549).  Saving model ...
Epoch 20, Batch 1 loss: 3.677615
Epoch 20, Batch 101 loss: 3.936015
Epoch 20, Batch 201 loss: 3.969816
Epoch 20, Batch 301 loss: 3.976090
Epoch: 20 	Training Loss: 3.981628 	Validation Loss: 3.896142
Epoch 21, Batch 1 loss: 4.023327
Epoch 21, Batch 101 loss: 3.981357
Epoch 21, Batch 201 loss: 3.983127
Epoch 21, Batch 301 loss: 3.984080
Epoch: 21 	Training Loss: 3.986262 	Validation Loss: 3.885974
Epoch 22, Batch 1 loss: 3.984540
Epoch 22, Batch 101 loss: 3.954956
Epoch 22, Batch 201 loss: 3.958741
Epoch 22, Batch 301 loss: 3.985363
Epoch: 22 	Training Loss: 3.981246 	Validation Loss: 3.875813
Validation loss decreased (3.876549 --> 3.875813).  Saving model ...
Epoch 23, Batch 1 loss: 4.052670
Epoch 23, Batch 101 loss: 3.960752
Epoch 23, Batch 201 loss: 3.954160
Epoch 23, Batch 301 loss: 3.970532
Epoch: 23 	Training Loss: 3.974799 	Validation Loss: 3.902927
Epoch 24, Batch 1 loss: 4.047044
Epoch 24, Batch 101 loss: 3.935894
Epoch 24, Batch 201 loss: 3.929808
Epoch 24, Batch 301 loss: 3.941484
Epoch: 24 	Training Loss: 3.941354 	Validation Loss: 3.854439
Validation loss decreased (3.875813 --> 3.854439).  Saving model ...
Epoch 25, Batch 1 loss: 3.782246
Epoch 25, Batch 101 loss: 3.960466
Epoch 25, Batch 201 loss: 3.941117
Epoch 25, Batch 301 loss: 3.934870
Epoch: 25 	Training Loss: 3.940361 	Validation Loss: 3.884810
Epoch 26, Batch 1 loss: 3.673846
Epoch 26, Batch 101 loss: 3.912244
Epoch 26, Batch 201 loss: 3.920259
Epoch 26, Batch 301 loss: 3.918994
Epoch: 26 	Training Loss: 3.917681 	Validation Loss: 3.866629
Epoch 27, Batch 1 loss: 4.060912
Epoch 27, Batch 101 loss: 3.908235
Epoch 27, Batch 201 loss: 3.892696
Epoch 27, Batch 301 loss: 3.900681
Epoch: 27 	Training Loss: 3.906797 	Validation Loss: 3.834383
Validation loss decreased (3.854439 --> 3.834383).  Saving model ...
Epoch 28, Batch 1 loss: 3.659374
Epoch 28, Batch 101 loss: 3.871794
Epoch 28, Batch 201 loss: 3.890930
Epoch 28, Batch 301 loss: 3.890855
Epoch: 28 	Training Loss: 3.888348 	Validation Loss: 3.876539
Epoch 29, Batch 1 loss: 3.252544
Epoch 29, Batch 101 loss: 3.830130
Epoch 29, Batch 201 loss: 3.851916
Epoch 29, Batch 301 loss: 3.870153
Epoch: 29 	Training Loss: 3.880702 	Validation Loss: 3.868705
Epoch 30, Batch 1 loss: 3.639014
Epoch 30, Batch 101 loss: 3.921535
Epoch 30, Batch 201 loss: 3.912106
Epoch 30, Batch 301 loss: 3.891545
Epoch: 30 	Training Loss: 3.894287 	Validation Loss: 3.804181
Validation loss decreased (3.834383 --> 3.804181).  Saving model ...
Epoch 31, Batch 1 loss: 3.877073
Epoch 31, Batch 101 loss: 3.853077
Epoch 31, Batch 201 loss: 3.859220
Epoch 31, Batch 301 loss: 3.868797
Epoch: 31 	Training Loss: 3.866691 	Validation Loss: 3.837158
Epoch 32, Batch 1 loss: 3.932338
Epoch 32, Batch 101 loss: 3.847612
Epoch 32, Batch 201 loss: 3.840028
Epoch 32, Batch 301 loss: 3.840554
Epoch: 32 	Training Loss: 3.841542 	Validation Loss: 3.805808
Epoch 33, Batch 1 loss: 3.814364
Epoch 33, Batch 101 loss: 3.814686
Epoch 33, Batch 201 loss: 3.817567
Epoch 33, Batch 301 loss: 3.854979
Epoch: 33 	Training Loss: 3.857601 	Validation Loss: 3.784923
Validation loss decreased (3.804181 --> 3.784923).  Saving model ...
Epoch 34, Batch 1 loss: 4.050500
Epoch 34, Batch 101 loss: 3.839726
Epoch 34, Batch 201 loss: 3.863915
Epoch 34, Batch 301 loss: 3.861587
Epoch: 34 	Training Loss: 3.864170 	Validation Loss: 3.773559
Validation loss decreased (3.784923 --> 3.773559).  Saving model ...
Epoch 35, Batch 1 loss: 4.018894
Epoch 35, Batch 101 loss: 3.789054
Epoch 35, Batch 201 loss: 3.807751
Epoch 35, Batch 301 loss: 3.808274
Epoch: 35 	Training Loss: 3.816551 	Validation Loss: 3.795639
Epoch 36, Batch 1 loss: 4.980113
Epoch 36, Batch 101 loss: 3.806926
Epoch 36, Batch 201 loss: 3.816932
Epoch 36, Batch 301 loss: 3.809095
Epoch: 36 	Training Loss: 3.812845 	Validation Loss: 3.762169
Validation loss decreased (3.773559 --> 3.762169).  Saving model ...
Epoch 37, Batch 1 loss: 3.819650
Epoch 37, Batch 101 loss: 3.789338
Epoch 37, Batch 201 loss: 3.790011
Epoch 37, Batch 301 loss: 3.798630
Epoch: 37 	Training Loss: 3.803276 	Validation Loss: 3.765598
Epoch 38, Batch 1 loss: 3.864088
Epoch 38, Batch 101 loss: 3.757014
Epoch 38, Batch 201 loss: 3.778924
Epoch 38, Batch 301 loss: 3.799101
Epoch: 38 	Training Loss: 3.796148 	Validation Loss: 3.775842
Epoch 39, Batch 1 loss: 4.124297
Epoch 39, Batch 101 loss: 3.769081
Epoch 39, Batch 201 loss: 3.779954
Epoch 39, Batch 301 loss: 3.787183
Epoch: 39 	Training Loss: 3.792635 	Validation Loss: 3.745866
Validation loss decreased (3.762169 --> 3.745866).  Saving model ...
Epoch 40, Batch 1 loss: 3.245607
Epoch 40, Batch 101 loss: 3.745193
Epoch 40, Batch 201 loss: 3.760329
Epoch 40, Batch 301 loss: 3.771701
Epoch: 40 	Training Loss: 3.778307 	Validation Loss: 3.759131
Epoch 41, Batch 1 loss: 3.470266
Epoch 41, Batch 101 loss: 3.731635
Epoch 41, Batch 201 loss: 3.741713
Epoch 41, Batch 301 loss: 3.745678
Epoch: 41 	Training Loss: 3.758569 	Validation Loss: 3.725338
Validation loss decreased (3.745866 --> 3.725338).  Saving model ...
Epoch 42, Batch 1 loss: 3.666461
Epoch 42, Batch 101 loss: 3.750484
Epoch 42, Batch 201 loss: 3.760497
Epoch 42, Batch 301 loss: 3.761008
Epoch: 42 	Training Loss: 3.762475 	Validation Loss: 3.766580
Epoch 43, Batch 1 loss: 3.474717
Epoch 43, Batch 101 loss: 3.762396
Epoch 43, Batch 201 loss: 3.757699
Epoch 43, Batch 301 loss: 3.759538
Epoch: 43 	Training Loss: 3.762031 	Validation Loss: 3.742422
Epoch 44, Batch 1 loss: 3.696681
Epoch 44, Batch 101 loss: 3.705737
Epoch 44, Batch 201 loss: 3.719455
Epoch 44, Batch 301 loss: 3.722574
Epoch: 44 	Training Loss: 3.728711 	Validation Loss: 3.693602
Validation loss decreased (3.725338 --> 3.693602).  Saving model ...
Epoch 45, Batch 1 loss: 3.734644
Epoch 45, Batch 101 loss: 3.757451
Epoch 45, Batch 201 loss: 3.744418
Epoch 45, Batch 301 loss: 3.750386
Epoch: 45 	Training Loss: 3.744381 	Validation Loss: 3.787005
Epoch 46, Batch 1 loss: 4.006459
Epoch 46, Batch 101 loss: 3.740195
Epoch 46, Batch 201 loss: 3.736324
Epoch 46, Batch 301 loss: 3.719512
Epoch: 46 	Training Loss: 3.722931 	Validation Loss: 3.696561
Epoch 47, Batch 1 loss: 3.600419
Epoch 47, Batch 101 loss: 3.683319
Epoch 47, Batch 201 loss: 3.703171
Epoch 47, Batch 301 loss: 3.721639
Epoch: 47 	Training Loss: 3.715032 	Validation Loss: 3.682416
Validation loss decreased (3.693602 --> 3.682416).  Saving model ...
Epoch 48, Batch 1 loss: 3.530738
Epoch 48, Batch 101 loss: 3.717556
Epoch 48, Batch 201 loss: 3.696714
Epoch 48, Batch 301 loss: 3.715632
Epoch: 48 	Training Loss: 3.720422 	Validation Loss: 3.705816
Epoch 49, Batch 1 loss: 3.477603
Epoch 49, Batch 101 loss: 3.613868
Epoch 49, Batch 201 loss: 3.648503
Epoch 49, Batch 301 loss: 3.668497
Epoch: 49 	Training Loss: 3.669135 	Validation Loss: 3.669412
Validation loss decreased (3.682416 --> 3.669412).  Saving model ...
Epoch 50, Batch 1 loss: 2.790202
Epoch 50, Batch 101 loss: 3.679237
Epoch 50, Batch 201 loss: 3.661862
Epoch 50, Batch 301 loss: 3.672854
Epoch: 50 	Training Loss: 3.668023 	Validation Loss: 3.692973
Epoch 51, Batch 1 loss: 4.175966
Epoch 51, Batch 101 loss: 3.650579
Epoch 51, Batch 201 loss: 3.641231
Epoch 51, Batch 301 loss: 3.661557
Epoch: 51 	Training Loss: 3.671620 	Validation Loss: 3.656515
Validation loss decreased (3.669412 --> 3.656515).  Saving model ...
Epoch 52, Batch 1 loss: 3.218865
Epoch 52, Batch 101 loss: 3.638751
Epoch 52, Batch 201 loss: 3.654962
Epoch 52, Batch 301 loss: 3.658901
Epoch: 52 	Training Loss: 3.664316 	Validation Loss: 3.611170
Validation loss decreased (3.656515 --> 3.611170).  Saving model ...
Epoch 53, Batch 1 loss: 3.720623
Epoch 53, Batch 101 loss: 3.613141
Epoch 53, Batch 201 loss: 3.655653
Epoch 53, Batch 301 loss: 3.654802
Epoch: 53 	Training Loss: 3.647606 	Validation Loss: 3.673790
Epoch 54, Batch 1 loss: 3.967995
Epoch 54, Batch 101 loss: 3.583606
Epoch 54, Batch 201 loss: 3.609357
Epoch 54, Batch 301 loss: 3.638215
Epoch: 54 	Training Loss: 3.634463 	Validation Loss: 3.639241
Epoch 55, Batch 1 loss: 4.342576
Epoch 55, Batch 101 loss: 3.653702
Epoch 55, Batch 201 loss: 3.610253
Epoch 55, Batch 301 loss: 3.630813
Epoch: 55 	Training Loss: 3.631083 	Validation Loss: 3.670284
In [25]:
# load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
model_scratch
Out[25]:
Net(
  (conv1): Conv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))
  (conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))
  (conv3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (fc1): Linear(in_features=6272, out_features=500, bias=True)
  (fc2): Linear(in_features=500, out_features=133, bias=True)
  (dropout): Dropout(p=0.33)
)

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.

In [28]:
def test(loaders, model, criterion, use_cuda):

    # monitor test loss and accuracy
    test_loss = 0.
    correct = 0.
    total = 0.

    model.eval()
    for batch_idx, (data, target) in enumerate(loader_scratch['test']):
        if use_cuda:
            data, target = data.cuda(), target.cuda()
        output = model(data)
        loss = criterion(output, target)
        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
        pred = output.data.max(1, keepdim=True)[1]
        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
        total += data.size(0)
            
            
    print('Test Loss: {:.6f}\n'.format(test_loss))

    print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
        100. * correct / total, correct, total))

# call test function    
test(loader_scratch, model_scratch, criterion_scratch, use_cuda)
Test Loss: 3.845329


Test Accuracy: 13% (114/836)

Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).

If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.

In [29]:
## TODO: Specify data loaders
train_dir = ('/data/dog_images/train')
valid_dir = ('/data/dog_images/valid')
test_dir =  ('/data/dog_images/test')




data_transforms = {'train': transforms.Compose([transforms.RandomResizedCrop(224),
                                     transforms.RandomHorizontalFlip(),
                                     transforms.RandomVerticalFlip(),
                                     transforms.RandomGrayscale(),
                                     transforms.ToTensor(),
                                     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                              std=[0.229, 0.224, 0.225]),
                                     ]),
                   
                   
                   'valid': transforms.Compose([transforms.Resize(256),
                                     transforms.CenterCrop(224),
                                     transforms.ToTensor(),
                                     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                              std=[0.229, 0.224, 0.225])]),
                   
                   'test': transforms.Compose([transforms.Resize(size=(224,224)),
                                     transforms.ToTensor(), 
                                     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                              std=[0.229, 0.224, 0.225])])
                    
}
train_data= datasets.ImageFolder(train_dir, transform=data_transforms['train'])
valid_data= datasets.ImageFolder(valid_dir, transform=data_transforms['valid'])
test_data= datasets.ImageFolder(test_dir, transform=data_transforms['test'])

loader_transfer={ 'train' : torch.utils.data.DataLoader(train_data, batch_size=batch_size,num_workers=num_workers, shuffle=True),
              'valid' : torch.utils.data.DataLoader(valid_data,batch_size=batch_size, num_workers=num_workers,shuffle=False),
              'test'  : torch.utils.data.DataLoader(test_data,batch_size=batch_size,num_workers=num_workers,shuffle=False)
    
}

(IMPLEMENTATION) Model Architecture

Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.

In [37]:
import torchvision.models as models
import torch.nn as nn

##Specify model architecture 
model_transfer = models.resnet50(pretrained=True)

    
for param in model_transfer.parameters():
    param.requires_grad = False

model_transfer.fc = nn.Linear(2048, 133, bias=True)
fc_parameters = model_transfer.fc.parameters()

for param in fc_parameters:
    param.requires_grad = True
use_cuda = torch.cuda.is_available()

if use_cuda:
    model_transfer = model_transfer.cuda()    

model_transfer
Out[37]:
ResNet(
  (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
  (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (relu): ReLU(inplace)
  (maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)
  (layer1): Sequential(
    (0): Bottleneck(
      (conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
      (downsample): Sequential(
        (0): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (1): Bottleneck(
      (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
    (2): Bottleneck(
      (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
  )
  (layer2): Sequential(
    (0): Bottleneck(
      (conv1): Conv2d(256, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
      (downsample): Sequential(
        (0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False)
        (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (1): Bottleneck(
      (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
    (2): Bottleneck(
      (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
    (3): Bottleneck(
      (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
  )
  (layer3): Sequential(
    (0): Bottleneck(
      (conv1): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
      (downsample): Sequential(
        (0): Conv2d(512, 1024, kernel_size=(1, 1), stride=(2, 2), bias=False)
        (1): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (1): Bottleneck(
      (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
    (2): Bottleneck(
      (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
    (3): Bottleneck(
      (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
    (4): Bottleneck(
      (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
    (5): Bottleneck(
      (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
  )
  (layer4): Sequential(
    (0): Bottleneck(
      (conv1): Conv2d(1024, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
      (downsample): Sequential(
        (0): Conv2d(1024, 2048, kernel_size=(1, 1), stride=(2, 2), bias=False)
        (1): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (1): Bottleneck(
      (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
    (2): Bottleneck(
      (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
  )
  (avgpool): AvgPool2d(kernel_size=7, stride=1, padding=0)
  (fc): Linear(in_features=2048, out_features=133, bias=True)
)

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

Here I tried different pretained models but decided to go with a ResNet Modell. First of all, the ResNet-architecture is highly accurate and deliever good results in Image Classification. Smaller ResNet scenarios such as ResNet18 and ResNet35 were not really suitable to the data since we have a rather big modell with 133 different classes. ResNet152 on the other hand would probably too deep for the task. Therefore I decided to use a prerained ResNet50.

The only modification i did, was adding a fully conected layer at the end of the architecture to specify the output of 133 to get the 133 different classes of dog breeds.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.

In [38]:
criterion_transfer = nn.CrossEntropyLoss()
optimizer_transfer = optim.Adam(model_transfer.fc.parameters(), lr=0.005)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.

In [39]:
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
    """returns trained model"""
    # initialize tracker for minimum validation loss
    valid_loss_min = np.Inf
    
    for epoch in range(1, n_epochs+1):
        # initialize variables to monitor training and validation loss
        train_loss = 0.0
        valid_loss = 0.0
        
        ###################
        # train the model #
        ###################
        model.train()
        for batch_idx, (data, target) in enumerate(loaders['train']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()

            # initialize weights to zero
            optimizer.zero_grad()
            
            output = model(data)
            
            # calculate loss
            loss = criterion(output, target)
            
            # back prop
            loss.backward()
            
            # grad
            optimizer.step()
            
            train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
            
            if batch_idx % 100 == 0:
                print('Epoch %d, Batch %d loss: %.6f' %
                  (epoch, batch_idx + 1, train_loss))
        
        ######################    
        # validate the model #
        ######################
        model.eval()
        for batch_idx, (data, target) in enumerate(loaders['valid']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## update the average validation loss
            output = model(data)
            loss = criterion(output, target)
            valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))

            
        # print training/validation statistics 
        print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
            epoch, 
            train_loss,
            valid_loss
            ))
        
        ## TODO: save the model if validation loss has decreased
        if valid_loss < valid_loss_min:
            torch.save(model.state_dict(), save_path)
            print('Validation loss decreased ({:.6f} --> {:.6f}).  Saving model ...'.format(
            valid_loss_min,
            valid_loss))
            valid_loss_min = valid_loss
            
    # return trained model
    return model

model_transfer = train(10, loader_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt')
# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load('model_transfer.pt'))
Epoch 1, Batch 1 loss: 5.046956
Epoch 1, Batch 101 loss: 4.483609
Epoch 1, Batch 201 loss: 3.711821
Epoch 1, Batch 301 loss: 3.302666
Epoch: 1 	Training Loss: 3.210194 	Validation Loss: 1.025607
Validation loss decreased (inf --> 1.025607).  Saving model ...
Epoch 2, Batch 1 loss: 2.079254
Epoch 2, Batch 101 loss: 2.022465
Epoch 2, Batch 201 loss: 1.937826
Epoch 2, Batch 301 loss: 1.932606
Epoch: 2 	Training Loss: 1.918378 	Validation Loss: 0.696391
Validation loss decreased (1.025607 --> 0.696391).  Saving model ...
Epoch 3, Batch 1 loss: 1.256059
Epoch 3, Batch 101 loss: 1.657472
Epoch 3, Batch 201 loss: 1.653010
Epoch 3, Batch 301 loss: 1.650782
Epoch: 3 	Training Loss: 1.674230 	Validation Loss: 0.660827
Validation loss decreased (0.696391 --> 0.660827).  Saving model ...
Epoch 4, Batch 1 loss: 1.382305
Epoch 4, Batch 101 loss: 1.564164
Epoch 4, Batch 201 loss: 1.585079
Epoch 4, Batch 301 loss: 1.607215
Epoch: 4 	Training Loss: 1.609196 	Validation Loss: 0.585767
Validation loss decreased (0.660827 --> 0.585767).  Saving model ...
Epoch 5, Batch 1 loss: 1.410226
Epoch 5, Batch 101 loss: 1.557904
Epoch 5, Batch 201 loss: 1.540772
Epoch 5, Batch 301 loss: 1.551095
Epoch: 5 	Training Loss: 1.555471 	Validation Loss: 0.566052
Validation loss decreased (0.585767 --> 0.566052).  Saving model ...
Epoch 6, Batch 1 loss: 1.571845
Epoch 6, Batch 101 loss: 1.421909
Epoch 6, Batch 201 loss: 1.457361
Epoch 6, Batch 301 loss: 1.490153
Epoch: 6 	Training Loss: 1.487494 	Validation Loss: 0.523394
Validation loss decreased (0.566052 --> 0.523394).  Saving model ...
Epoch 7, Batch 1 loss: 1.534393
Epoch 7, Batch 101 loss: 1.352528
Epoch 7, Batch 201 loss: 1.423455
Epoch 7, Batch 301 loss: 1.450710
Epoch: 7 	Training Loss: 1.460188 	Validation Loss: 0.507073
Validation loss decreased (0.523394 --> 0.507073).  Saving model ...
Epoch 8, Batch 1 loss: 1.517252
Epoch 8, Batch 101 loss: 1.298041
Epoch 8, Batch 201 loss: 1.362540
Epoch 8, Batch 301 loss: 1.412508
Epoch: 8 	Training Loss: 1.409280 	Validation Loss: 0.541358
Epoch 9, Batch 1 loss: 1.216233
Epoch 9, Batch 101 loss: 1.384844
Epoch 9, Batch 201 loss: 1.381542
Epoch 9, Batch 301 loss: 1.400338
Epoch: 9 	Training Loss: 1.399104 	Validation Loss: 0.547388
Epoch 10, Batch 1 loss: 1.177737
Epoch 10, Batch 101 loss: 1.345815
Epoch 10, Batch 201 loss: 1.366250
Epoch 10, Batch 301 loss: 1.395158
Epoch: 10 	Training Loss: 1.384927 	Validation Loss: 0.549232

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.

In [40]:
test(loader_transfer, model_transfer, criterion_transfer, use_cuda)
Test Loss: 0.681475


Test Accuracy: 79% (661/836)

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.

In [46]:
### Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from PIL import Image
import torchvision.transforms as transforms

def load_input_image(img_path):    
    image = Image.open(img_path).convert('RGB')
    prediction_transform = transforms.Compose([transforms.Resize(size=(224, 224)),
                                     transforms.ToTensor(), 
                                     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                              std=[0.229, 0.224, 0.225])])
    
    # discard the transparent, alpha channel (that's the :3) and add the batch dimension
    image = prediction_transform(image)[:3,:,:].unsqueeze(0)
    return image


class_names = [item[4:].replace("_", " ") for item in loader_transfer['train'].dataset.classes]


def predict_breed_transfer(model, class_names, img_path):
    # load the image and return the predicted breed
    img = load_input_image(img_path)
    model = model.cuda()
    model.eval()
    idx = torch.argmax(model(img))
    return class_names[idx]
In [ ]:
 

Step 5: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and human_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [ ]:
 
In [42]:
### Writing the algorithm
### Feel free to use as many code cells as needed.

def run_app(img_path):
    human = face_detector(img_path)
    dog = dog_detector(img_path)
    img = Image.open(img_path)
    plt.imshow(img)
    plt.show()
    if dog_detector(img_path) == True:
        prediction = predict_breed_transfer(model_transfer, class_names, img_path)
        print("This is a dog. It is a {}.".format(prediction))  
    elif face_detector(img_path) > 0:
        prediction = predict_breed_transfer(model_transfer, class_names, img_path)
        print("This is a Human.")
    else:
        print("Neither a dog nor a human.")
In [43]:
for img_file in os.listdir('./images'):
    img_path = os.path.join('./images', img_file)
    run_app(img_path)
This is a dog. It is a Welsh springer spaniel.
This is a Human.
This is a dog. It is a Labrador retriever.
This is a dog. It is a Curly-coated retriever.
Neither a dog nor a human.
This is a dog. It is a Brittany.
This is a dog. It is a Labrador retriever.
This is a dog. It is a Boykin spaniel.
This is a dog. It is a Entlebucher mountain dog.
This is a dog. It is a Labrador retriever.

Step 6: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

  1. First of all, I think that the a bigger dataset for training, validation and testing would be more suitable considering the 133 different output classes. Also some dog breeds vary only in small details and especially puppy images can lead to missclassification if there is not enough training data. With more training data it would also be possible to train emotions in humans faces, so that the modell would detect a human even when his face looks different. This problem of not being able to detect emotion-distorted faces occurred when testing my model.
  1. One way to improve the accuracy of the model even more, would be a training with more epochs. In the model_scratch i had to train the model for more than 50 epochs to receive suitable results. With the ResNet model i only used 10 epochs and got a accuracy of 79%. More training could mean that the model would be even better.
  1. Lastly another thing i learned by building my own model, is the importance of image augmentation. We could perform more data augmentation with random croping, rotating, coloring and flipping to train different scenarios. This could help to make the performance of the model even better.
In [45]:
## Execute the algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

## suggested code, below
for file in np.hstack((human_files[999:1011], dog_files[599:611])):
    run_app(file)
This is a Human.
This is a Human.
This is a Human.
This is a Human.
This is a Human.
This is a Human.
This is a Human.
This is a Human.
This is a Human.
This is a Human.
This is a Human.
Neither a dog nor a human.
This is a dog. It is a Parson russell terrier.
This is a dog. It is a Parson russell terrier.
This is a dog. It is a Parson russell terrier.
This is a dog. It is a Parson russell terrier.
This is a dog. It is a Parson russell terrier.
This is a dog. It is a Smooth fox terrier.
This is a dog. It is a Parson russell terrier.
This is a dog. It is a Parson russell terrier.
This is a dog. It is a Parson russell terrier.
This is a dog. It is a Parson russell terrier.
This is a dog. It is a Parson russell terrier.
This is a dog. It is a Parson russell terrier.
In [ ]: